package com.hqm.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hqm.meta.DeleteMsg;
import com.hqm.meta.Product;
import com.hqm.meta.Transaction;
import com.hqm.meta.User;
import com.hqm.service.ProductService;
import com.hqm.service.TransactionService;

@Controller
public class ProductController {
	
	private static final Log logger = LogFactory.getLog(ProductController.class);
	
	@Resource
	ProductService productService;
	
	@Resource
	TransactionService transactionService;
	
	/**
	 * 发布商品
	 * 只有卖家才能访问
	 * @param title
	 * @param summary
	 * @param detail
	 * @param price
	 * @param image
	 * @param session
	 * @param model
	 * @return 
	 */
	@RequestMapping(value = "/publicSubmit", method = RequestMethod.POST)
	public String publicProduct(@RequestParam String title, 
			@RequestParam String summary, @RequestParam String detail,
			@RequestParam Double price, @RequestParam String image,
			HttpSession session, Model model) {
		logger.info("publicProduct called");
		
		User user = (User)session.getAttribute("user");
		if (user == null || user.getUsertype() != 1) {
			return new PageController().toLogIn();
		} 
		
		Product product = new Product();
		product.setTitle(title);
		product.setSummary(summary);
		product.setDetail(detail);
		product.setPrice(price);
		product.setIcon(image);
		
		Boolean isAdd = productService.add(product);
		Product productInDB = productService.getProduct(product.getTitle());
		
		if (isAdd) {
			model.addAttribute("product", productInDB);
		} else {
			model.addAttribute("product", null);
		}
		
		return "publicSubmit";
	}
	
	/**
	 * 商品详情展示
	 * 根据登录用户类型不同，添加不同的模型数据
	 * @param request
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/show", method = RequestMethod.GET)
	public String showProduct(HttpServletRequest request,
			HttpSession session, Model model) {
		logger.info("showProduct called");
		
		Integer id = Integer.parseInt(request.getParameter("id"));
		Product product = productService.getProduct(id);
		product.setBuyNum(1);
		
		User user = (User)session.getAttribute("user");
		if (user != null && user.getUsertype() == 0) {
			List<Transaction> transactions;
			try {
				transactions = transactionService.getTrx(product, user);
				if (transactions.isEmpty()) {
					product.setIsBuy((byte)0);
					product.setBuyPrice(product.getPrice());
				} else {
					product.setIsBuy((byte)1);
					product.setBuyPrice(transactions.get(0).getPrice());
					product.setBuyNum(transactionService.getProductBuyNum(product, user));
				}
			} catch (Exception e) {
				logger.info(e.getMessage());
			}
		}

		//添加模型数据
		model.addAttribute("product", product);
		model.addAttribute("user", user);
		
		return "show";
	}
	
	/**
	 * 处理卖家对商品的删除
	 * @param productId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/api/delete", method = RequestMethod.POST)
	public DeleteMsg deleteProduct(@RequestParam("id") Integer productId) {
		logger.info("deleteProduct called");
		
		DeleteMsg deleteMsg = new DeleteMsg();
		Boolean isRemove = productService.remove(productId);
		
		if (isRemove) {
			deleteMsg.setCode(HttpServletResponse.SC_OK);
			deleteMsg.setMessage("删除成功");
			deleteMsg.setResult(true);
		} else {
			deleteMsg.setCode(HttpServletResponse.SC_ACCEPTED);
			deleteMsg.setMessage("删除失败");
			deleteMsg.setResult(false);
		}
		
		return deleteMsg;
	}
	
	/**
	 * 提交卖家对商品的编辑结果
	 * @param productId
	 * @param title
	 * @param summary
	 * @param detail
	 * @param price
	 * @param image
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/editSubmit", method = RequestMethod.POST)
	public String editProduct(@RequestParam("id") Integer productId, @RequestParam String title, 
			@RequestParam String summary, @RequestParam String detail,
			@RequestParam Double price, @RequestParam String image,
			HttpSession session, Model model) {
		logger.info("editProduct called");
		
		User user = (User)session.getAttribute("user");
		if (user == null || user.getUsertype() != 1) {
			return new PageController().toLogIn();
		} 
		
		Product product = new Product();
		product.setId(productId);
		product.setTitle(title);
		product.setSummary(summary);
		product.setDetail(detail);
		product.setPrice(price);
		product.setIcon(image);
		
		Boolean isUpdate = productService.update(product);
		Product productInDB = productService.getProduct(productId);
		
		if (isUpdate) {
			model.addAttribute("product", productInDB);
		} else {
			model.addAttribute("product", null);
		}
		
		return "publicSubmit";
	}
}
